import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Server;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.ServletException;

/**
 * @author yexi
 */
public class TomcatServer {

    private static final int PORT = 8080;
    private static final String CONTEXT_PATH = "/";
    /**
     * WEB-INF目录所处的目录，可自定义，这里直接使用编译输出目录充当
     */
    private static final String WEB_INF_PATH = Thread.currentThread().getContextClassLoader().getResource("").getPath();

    public static void main(String[] args) throws ServletException, LifecycleException {
        // 覆写jdk日志底层使用的配置。激活debug日志级别，从而查看更多tomcat底层执行的日志。
        System.setProperty("java.util.logging.config.file", ClassLoader.getSystemResource("logging.properties").getFile());
        Tomcat tomcat = buildSimpleTomcat();
        System.out.println("测试地址: localhost:" + PORT + "/hello");
        tomcat.getServer().await();
    }

    /**
     * 尽可能用最简单的代码实现一个自定义启动 tomcat 的demo入门
     */
    static Tomcat buildSimpleTomcat() throws ServletException, LifecycleException {
        Tomcat tomcat = new Tomcat();
        tomcat.setBaseDir(WEB_INF_PATH);
        tomcat.setPort(PORT);
        tomcat.addWebapp(CONTEXT_PATH, WEB_INF_PATH);
        tomcat.enableNaming();
        // 9.x版本的start()去掉了getConnector()，需要手动调用下。8.x版本可以没有。
        tomcat.getConnector();
        tomcat.start();
        return tomcat;
    }

    /**
     * 基于 Tomcat 内部的每个对象属性进行更为详细的介绍和构建
     */
    static Tomcat buildComplexTomcat() throws ServletException, LifecycleException {
        Tomcat tomcat = new Tomcat();
        tomcat.setBaseDir(WEB_INF_PATH);
        tomcat.setPort(PORT);

        Server server = tomcat.getServer();

        Engine engine = tomcat.getEngine();
        engine.setBackgroundProcessorDelay(-1);

        Host host = tomcat.getHost();
        host.setAutoDeploy(true);

        tomcat.addWebapp(CONTEXT_PATH, WEB_INF_PATH);
        tomcat.enableNaming();
        tomcat.getConnector();
        tomcat.start();
        return tomcat;
    }


}
